<?php

namespace app\api\service;
use addons\tongcheng\model\UserInfoModel;
use app\admin\model\Addresses;
use app\admin\model\commission\Log;
use app\admin\model\commission\Rate;
use app\admin\model\Coupon;
use app\admin\model\CouponRecord;
use app\admin\model\Details;
use app\admin\model\Order;
use app\admin\model\order\Operations;
use app\admin\model\User;
use app\api\controller\Index;
use app\common\controller\Api;
use app\admin\model\Products;
use app\common\model\Area;
use think\Db;
error_reporting(E_ERROR);
class OrderService
{


    public function createOrder($params)
    {
        $user=User::where('id','=',$params['user_id'])->find();
        if($user['role']!='user'){
            fail('非用户身份无法下单');
        }
        $order_no = order_no();
        Db::startTrans();
        try {

            // 检查用户在10秒内是否有相同商品的未支付订单
            $existingOrder = Order::
                where('user_id', $params['user_id'])
                ->where('order_status', 0) // 假设 0 表示待支付状态
                ->where('goodid', $params['good_id'])
                ->where('createtime', '>', time() - 5) // 过去10秒内
                ->find();
            if ($existingOrder) {
                fail('您点击的太快了');
            }


            //判断是商品还是技师
            if($params['type']==0){
                $products = Products::where('id', '=', $params['good_id'])->field('id,price,image img,product_name name')->find();
              }else if($params['type']==1){
                $products = Details::where('id', '=', $params['good_id'])->field('id,price,img,name')->find();
            }else{
                fail('下单异常');
            }
            if($products==null){
                fail('商品不存在');
            }
            if($products['price']<=0){
                fail('商品金额异常');
            }

            $order_type=$params['type'];
            unset($params['type']);

            //有优惠券
            if (isset($params['coupon_record_id']) && $params['coupon_record_id'] != "") {
                $this->loadCoupon(['coupon_record_id' => $params['coupon_record_id'], 'amount' => $products['price'],'user_id'=>$params['user_id']]);
                $coupon_amount = $this->fields['coupon_discount'];
            } else {
                $coupon_amount = 0;
            }
            // 自动取消分钟
            $auto_cancel_unpaid_minutes = 180;
            $paid_amount = $products['price'] - $coupon_amount;
            if ($paid_amount <= 0) {
                $paid_amount = 0.01;
            }
            // 创建订单
            $address = Addresses::where('id', '=', $params['adr_id'])->find();
            if (!$address) {
                fail('请选择地址');
            }
            $provinceName = Area::where('id', $address['province_id'])->value('name');
            $cityName = Area::where('id', $address['city_id'])->value('name');
            $districtName = Area::where('id', $address['district_id'])->value('name');

            $order = Order::insertGetId([
                'user_id' => $params['user_id'],
                'order_no' => $order_no,
                'order_type' => $order_type == 0 ? 'child' : 'senior',
                'amount' => $products['price'],
                'coupon_amount' => $coupon_amount,
                'paid_amount' => $paid_amount,
                'order_status' => 0,
                'riderid'=>$order_type == 0 ? null : $params['good_id'],
                'receiv_time'=>$order_type == 0 ? null : time(),
                'goodid'=>$params['good_id'],
                'goodname'=>$products['name'],
                'goodimage'=>$products['img'],
                'name'=>$address['name'],
                'phone'=>$address['phone'],
                'createtime'=>time(),
                'goodtype'=>$order_type,
                'address' => $provinceName . $cityName . $districtName . $address['address'],
                'coupon_record_id' => isset($params['coupon_record_id']) ? $params['coupon_record_id'] : null,
                // 支付过期时间
                'expire_pay_time' => $auto_cancel_unpaid_minutes > 0 ? time() + $auto_cancel_unpaid_minutes * 60 : 0,
            ],'IGNORE');

            // 使用优惠券，更改优惠券状态
            if (!empty($params['coupon_record_id'])) {
                Coupon::useCoupon($params['coupon_record_id']);
            }
            // 订单操作记录
            Operations::create([
                'order_id' => $order['id'],
                'action' => '创建订单',
                'user_id' => $params['user_id'],
                'description' => '创建订单',
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            Db::commit();
        } catch (\think\Exception\HttpResponseException $e) {
            Db::rollback();
            $data = $e->getResponse()->getData();
            fail($data['msg'] ?? $e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            fail($e->getMessage());
        }

        return $order;
    }


    protected function loadCoupon($params)
    {
        if (empty($params['coupon_record_id'])) {
            return;
        }
        if (!is_numeric($params['coupon_record_id'])) {
            fail('优惠券ID格式错误');
        }

        $coupon_record_id = intval($params['coupon_record_id']);
        if ($coupon_record_id) {
            $couponRecord = CouponRecord::get($coupon_record_id, ['coupon']);
            if (!$couponRecord) {
                fail("优惠券记录不存在");
            }
            if ($couponRecord['user_id'] != $params['user_id']) {
                fail("优惠券记录非当前用户所有 - ");
            }

            if ($couponRecord['status'] != 0) {
                fail("优惠券已使用或已过期");
            }
            if ($couponRecord['coupon']['start_time'] > time()) {
                fail("优惠券未到使用时间");
            }
            if ($couponRecord['coupon']['end_time'] < time()) {
                fail("优惠券已过期");
            }

            if ($couponRecord['min_money'] > $params['amount']) {
                fail("优惠券不满足使用条件");
            }
            $discount = min($params['amount'], $couponRecord['money']);
            $this->fields['coupon_id'] = $couponRecord['coupon_id'];
            $this->fields['coupon_record_id'] = $couponRecord['id'];
            $this->fields['coupon_discount'] = $discount;
        }
    }


    /**
     * 发起支付
     * @return mixed
     */
    public static function getPayment($id,$uid)
    {
        $order=Order::where('id','=', $id)->find();
        if (!$order) {
            fail('订单不存在');
        }
        if ($order['order_status'] != 0) {
            fail('订单状态错误');
       }
        $user_info = User::where('id','=',$uid)->find();
        if (!$user_info || !$user_info['openid']) {
            fail('用户信息不存在，或未绑定微信，请重新登录后再试');
        }
        return \addons\epay\library\Service::submitOrder($order['paid_amount'], $order['order_no'], "wechat", $order['goodname'], request()->domain() . '/api/notify/pay', "", "miniapp",$user_info['openid']);

    }

    //取消订单
    public function cance_order($params)
    {

        $order = DeliveryOrder::getById($params['id']);
        if ($order['order_status'] != 0 && $order['order_status'] != 1) {
            tongcheng_fail('当前订单无法操作');
        }
        Db::startTrans();
        $order_status = $order['order_status'] == 0 ? 5 : 6;
        $result = DeliveryOrder::where('id', $params['id'])->where('order_status', $order['order_status'])->update([ 'order_status' => $order_status]);
        if($result>0&&$order_status==6){
            $money=$order['porder_id']!=null?$order['average_amount']:$order['paid_amount'];
            DeliveryOrderRefundModel::create(['order_id'=>$params['id'],'user_id'=>$order['user_id'],'user_role'=>'CUSTOMER','refund_no'=>tongcheng_generate_no('D'),'refund_fee'=>$money,'refund_channel'=>'WECHAT','status'=>0,'remark'=>$params['cancel_reason'],'cancel_proof_image'=>$params['cancel_proof_image']]);
        }
        if($result>0&&$order_status==5){
        $this->return_co_av($params['id']);
        }
        DB::commit();
        return $result;
    }


    //取消订单退回 优惠券和释放时间段
    public function return_co_av($id){
        $order = Order::getById($id);
        if ($order['coupon_record_id'] > 0) {
            CouponRecord::where('id', '=', $order['coupon_record_id'])->update(['status' => 0]);
        }

    }






        /*
      * 分佣
      */
    public function fenyong($id){
        db::startTrans();
        $order = Order::where('id', '=', $id)->find();
        $ordermoeny=$order['amount'];
        $rate=new Rate();
        $commission=$rate->getCommission($order['amount']);
        $user=User::where('id','=',$order['user_id'])->find();
        $rate=0;
        if($user['pid']!==null&&$user['pid']!==0){
            //直推奖
            Index::index(['user_id'=>$user['pid'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'parent','money'=>$commission['parent']*$ordermoeny/100,'rate'=>$commission['parent'],'order_money'=>$ordermoeny,'type'=>'直推奖']);
            $rate+=$commission['parent'];
            $p_user=User::where('id','=',$user['pid'])->find();
            if($p_user['pid']!==null&&$p_user['pid']!==0){
                //间推奖
                Index::index(['user_id'=>$p_user['pid'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'parent2','money'=>$commission['parent2']*$ordermoeny/100,'rate'=>$commission['parent2'],'order_money'=>$ordermoeny,'type'=>'间推奖']);
                $rate+=$commission['parent2'];
            }
        }
        //咨询师
        $riderdetial=Details::where('id','=',$order['riderid'])->find();
        $rider=User::where('id','=',$riderdetial['user_id'])->find();
        //代理商分佣
        if($rider['agent_id']!==null&&$rider['agent_id']!==""){
            Index::index(['user_id'=>$rider['agent_id'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'agent','money'=>$commission['agent']*$ordermoeny/100,'rate'=>$commission['agent'],'order_money'=>$ordermoeny,'type'=>'代理分佣']);
            $rate+=$commission['agent'];
        }
        //经商商分佣 如果代理商不存在 给经销商上级
        if($rider['room_id']!==null&&$rider['room_id']!==""){
            Index::index(['user_id'=>$rider['room_id'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'room','money'=>$commission['room']*$ordermoeny/100,'rate'=>$commission['room'],'order_money'=>$ordermoeny,'type'=>'陪伴室分佣']);
            $rate+=$commission['room'];
            $room=User::where('id','=',$rider['room_id'])->find();
            if($room['agent_id']!=null&&$room['agent_id']!==""){
                Index::index(['user_id'=>$room['agent_id'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'agent','money'=>$commission['agent']*$ordermoeny/100,'rate'=>$commission['agent'],'order_money'=>$ordermoeny,'type'=>'代理分佣']);
                $rate+=$commission['agent'];
            }
        }
        //平台
        Index::index(['order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'platform','money'=>$commission['platform']*$ordermoeny/100,'rate'=>$commission['platform'],'order_money'=>$ordermoeny,'type'=>'平台']);
        $rate+=$commission['platform'];
        //陪伴师
        Index::index(['user_id'=>$rider['id'],'order_id'=>$order['id'],'order_user_id'=>$order['user_id'],'role'=>'companion','money'=>(100-$rate)*$ordermoeny/100,'rate'=>(100-$rate),'order_money'=>$ordermoeny,'type'=>'陪伴师收益']);
        db::commit();
    }

}